<?php

namespace App\Models\CacheModel\ai_chat_room;

use App\Models\CacheModel\AppConfig;
use App\Models\CacheModel\ZlUserVip;
use App\Models\Api\BaseCache;
use AstroTool\Cache\CacheManage;

class AiChatUserDuration extends BaseCache
{
    protected $table = 'ai_chat_room.ai_chat_user_duration';

    protected $cacheModel = 'ai_chat_room.chat_user_duration';

    /**
     * 保存数据
     * @param array $data
     * @return int
     */
    public function SaveData(array $data)
    {
        try
        {
            $id = $this->insertGetId($data);

            return (int)$id;
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            return 0;
        }
    }

    public function UpdateData(int $uid, array $updateData)
    {
        try
        {
            $this->where(['uid' => $uid])->update($updateData);

            CacheManage::getInstance()->setCacheConfig($this->cacheModel, $uid)->setCacheTime(10)->setCache($updateData);
            return true;
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            return false;
        }
    }

    /**
     * @param array $ids
     * @param array|null $type
     * @param string $sortType
     * @return array
     */
    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        // 获取未删除 的数据
        try
        {
            $data = $this->where(['uid' => ['in', $ids]])->column('*', 'id');
        }
        catch (\Exception $e)
        {
            $data = [];
        }
        return $data;
    }


    public function batchGetInfoByIds($cids, $field = [])
    {
        $resData = parent::batchGetInfoByIds($cids, $field);

        return $this->dataInit($resData);
    }

    /**
     * 数据初始化
     * @param array $data
     * @return array
     */
    public function dataInit(array $data)
    {
        foreach ($data as $index => $itemData)
        {
            $data[$index] = arrayKeyData2int($itemData, ['id', 'uid', 'duration', 'total_duration', 'status', 'last_send_time', 'start_time', 'end_time', 'create_time', 'update_time']);
        }

        return $data;
    }

    /**
     * 获取用户陪聊时长信息
     * @param int $uid
     * @return int[]|mixed
     * @throws \Exception
     */
    public function getChatUserDurationData(int $uid)
    {
        $detail = $this->getInfoById($uid);
        if (!$detail)
        {
            $nowTime = time();
            $detail = [
                'uid' => $uid,
                'duration' => 180,
                'total_duration' => 180,
                'status' => 0,
                'last_send_time' => 0,
                'start_time' => 0,
                'end_time' => 0,
                'create_time' => $nowTime,
                'update_time' => $nowTime,
            ];

            $detail['id'] = $this->SaveData($detail);
        }
        // 获取 vip 时长
        $detail['vip_duration'] = $this->getUserVipDuration($uid);
        $detail['res_duration'] = $detail['vip_duration'] + $detail['duration'];

        return $detail;
    }

    /**
     * 获取用户剩余时长
     * @param int $uid
     * @param bool $isEnd // 是否进行结算
     * @return array
     * @throws \Exception
     */
    public function getUserDuration(int $uid, bool $isEnd = false)
    {
        $durationData = $this->getChatUserDurationData($uid);
        if ($durationData['status'] === 1)
        {
            $nowTime = time();
            $d1 = $durationData['last_send_time'] - $durationData['start_time'];
            $d1 = max($d1, 0);
            $d2 = $nowTime - $durationData['last_send_time'];
            $d2 = min($d2, 30); // 进行中 最多30秒
            $d = $d1 + $d2;
            if ($isEnd && $d >= 30)
            {   // 结束
                $res = (new AiChatUserDurationChangeRecord())->userDurationDec($durationData, $d);
                $updateData = [
                    'status' => 0,
                    'end_time' => $nowTime,
                ];
                if ($res['use_duration'] > 0)
                {
                    $updateData['duration'] = $durationData['duration'] - $res['use_duration'];
                }
                $this->updateData($uid, $updateData);
                $durationData['status'] = 0;
            }
            $durationData['res_duration'] = $durationData['res_duration'] - $d;
        }

        return [
            'status' => $durationData['status'],
            'res_duration' => $durationData['res_duration'],
        ];
    }

    /**
     * 用户时长 暂停
     * @param int $uid
     * @throws \Exception
     */
    public function userDurationEnd(int $uid)
    {
        $durationData = $this->getChatUserDurationData($uid);
        if ($durationData['status'] === 1)
        {
            $nowTime = time();
            $d1 = $durationData['last_send_time'] - $durationData['start_time'];
            $d1 = max($d1, 0);
            $d2 = $nowTime - $durationData['last_send_time'];
            $d2 = min($d2, 30); // 进行中 最多30秒
            $d = $d1 + $d2;
            if ($d > 0)
            {   // 结束
                $res = (new AiChatUserDurationChangeRecord())->userDurationDec($durationData, $d);
                $updateData = [
                    'status' => 0,
                    'end_time' => $nowTime,
                ];
                if ($res['use_duration'] > 0)
                {
                    $updateData['duration'] = $durationData['duration'] - $res['use_duration'];
                }
                $this->updateData($uid, $updateData);
            }

            $durationData['res_duration'] = $durationData['res_duration'] - $d;
        }

        return $durationData['res_duration'];
    }

    /**
     * 获取用户剩余时长
     * @param int $uid
     * @return int
     * @throws \Exception
     */
    public function getUserVipDuration(int $uid)
    {
        $vipLevel = (new ZlUserVip())->getUserVipLevel($uid);
        if ($vipLevel)
        {
            $aiChatRoomConfig = (new AppConfig())->configInfo('ai_chat_room');
            $vipFreeDurationToday = $aiChatRoomConfig['vip_free_duration_today'] ?? 0;
            $vipFreeDuration = $vipFreeDurationToday * 60;
            //  获取vip 已使用时长
            $useDutarion = (new AiChatUserDurationChangeRecord())->getTodayVipUseDuration($uid);
            return max($vipFreeDuration - $useDutarion, 0);
        } else
        {
            return 0;
        }
    }

    /**
     * 用户聊天 陪聊中
     * @param int $uid
     * @return void
     * @throws \Exception
     */
    public function userDurationStart(int $uid)
    {
        $durationData = $this->getChatUserDurationData($uid);
        $nowTime = time();
        if ($durationData['status'] === 1)
        {
            $d1 = $durationData['last_send_time'] - $durationData['start_time'];
            $d1 = max($d1, 0);
            $d2 = $nowTime - $durationData['last_send_time'];
            $d2 = min($d2, 30); // 进行中 最多30秒
            $d = $d1 + $d2;
            if ($d >= 60 || $d2 >= 30)
            {   // 陪聊中 1分钟 结算一次
                $res = (new AiChatUserDurationChangeRecord())->userDurationDec($durationData, $d);
                $updateData = [
                    'last_send_time' => $nowTime,
                    'start_time' => $nowTime,
                    'end_time' => $nowTime,
                ];
                if ($res['use_duration'] > 0)
                {
                    $updateData['duration'] = $durationData['duration'] - $res['use_duration'];
                }
            } else
            {
                $updateData = [
                    'last_send_time' => $nowTime,
                ];
            }
        } else
        {
            $updateData = [
                'status' => 1,
                'last_send_time' => $nowTime,
                'start_time' => $nowTime,
            ];
        }
        // 更新信息
        $this->updateData($uid, $updateData);
    }
}
